<!-- 这是首页 -->
<template>
  <div>
    <van-nav-bar title="首页" left-text="" right-text="发布" @click-right="goPublic"/>
<!--    轮播图-->
    <van-swipe :autoplay="3000">
      <van-swipe-item v-for="(image, index) in images" :key="index">
        <img v-lazy="image"  style="width: 100vw;height: 300px;object-fit: cover"/>
      </van-swipe-item>
    </van-swipe>
    <van-empty description="还没有人发布内容，快来发布吧~" v-if="list.length==0"/>
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list :finished="page == total" finished-text="没有更多了" @load="onLoad" style="padding-bottom: 50px;">
        <!--        圈子显示部分-->
        <div class="x" style="margin:25px 15px ;" v-for="(item, index) in list" :key="index">
          <!-- <img :src="item.avatar" alt="Avatar" class="avatar" /> -->
          <!--          头像-->
          <van-image radius="4" fit="cover" width="50" height="50" :src="item.avatar"/>
          <div class="y flex" style="margin-left: 10px;">
            <!--            昵称-->
            <div class="username">{{ item.nickname }}</div>
            <!--            文案-->
            <div class="content-text">{{ item.content }}</div>
            <!--            图片显示部分-->
            <van-grid :column-num="3" style="margin:8px 0px" v-if="item.images.length > 0" :gutter="1">
              <van-image v-for="(img,index) in item.images" :key="index" style="margin: 1px;"
                         @click="ImagePreview(item.images, index)" radius="4" width="100" height="100" :src="img"
                         fit="cover"/>
            </van-grid>

            <div class="x" style="align-items: center;">
              <!--              时间-->
              <div class="timestamp flex">{{ parse(item.time) }}</div>
              <!--              点赞部分-->
              <van-popover placement="left" v-model="item.showPopover" theme="dark" trigger="click">
                <template #reference>
                  <van-icon name="ellipsis"/>
                </template>
                <div class="x common">
                  <div class="x " @click="like(item,index)" style="margin-right: 20px;align-items: center;">
                    <!--                    如果没点赞-->
                    <van-icon name="like-o" size="20" v-if="item.status !=1"/>
                    <!--                    点赞了-->
                    <van-icon name="like" size="20" v-if="item.status ==1" color="#DF0029"/>
                    <div>{{ item.status != 1 ? '点赞' : '取消' }}</div>
                  </div>


                  <div class="x" style="align-items: center;" @click="showComments(item,index)">
                    <van-icon name="comment-o" size="20"/>
                    <div>评论</div>
                  </div>

                </div>
              </van-popover>
            </div>
            <!--            位置部分-->
            <div class="x" style="align-items: center;color: #999;font-size: 12px" v-if="item.location">
              <van-icon name="location" color="#999"/>
              {{ item.location }}
            </div>
            <!--            点赞用户显示部分-->
            <div class="likeUsers" v-if="item.likeUsers">
              <van-icon name="like-o" size="14" color="#0c3a96"/>
              {{ item.likeUsers }}
            </div>
            <!--           评论的用户列表-->
            <div class="common-root" v-if="item.comments.length>0">
              <!--              comments-->
              <div class="common-friends" v-for="(str, i) in item.comments" :key="i" @click="showReply(str,index)">
                <div>
                  <img :src="str.avatar" style="height: 15px;width: 15px;border-radius: 3px;margin-right: 3px"/>
                  <span class="common-nickname">{{ str.nickname }}<span style="color: #333333;margin: 0 4px;"
                                                                        v-if="str.reply_id>0">回复</span>{{
                      str.replyNickname
                    }}:</span>
                  <span class="common-content">
                    {{ str.content }}
                  </span>
                  <span style="margin-left: 8px;font-size: 12px;color: #666666">
                    {{ parse(str.time) }}
                  </span>
                </div>

              </div>
            </div>
          </div>

        </div>
      </van-list>
    </van-pull-refresh>
    <!--            底部评论输入框-->
    <van-popup v-model="showComment" position="bottom" :style="{ height: '100px' }">
      <!--      <van-field v-model="comment" placeholder="评论内容"/>-->
      <div style="position: relative">
        <van-field v-model="comment" rows="2" autosize type="textarea" maxlength="250" placeholder="这一刻的想法..."
                   show-word-limit>
        </van-field>
        <van-button @click="Comment" size="mini" style="top: 10px;right: 10px;position: absolute">确认</van-button>
      </div>

    </van-popup>
    <!--            底部回复评论输入框-->
    <van-popup v-model="showReplyComment" position="bottom" :style="{ height: '100px' }">
      <!--      <van-field v-model="comment" placeholder="评论内容"/>-->
      <div style="position: relative">
        <van-field v-model="comment" rows="2" autosize type="textarea" maxlength="250"
                   :placeholder="'回复  '+commentItem.nickname "
                   show-word-limit>
        </van-field>
        <van-button @click="Comment" size="mini" style="top: 10px;right: 10px;position: absolute">回复</van-button>
      </div>

    </van-popup>
    <!--    点击评论弹出框模块-->
    <van-action-sheet
        @select="onSelect"
        v-model="showReplys"
        :actions="actions"
        cancel-text="取消"
    />
  </div>
</template>

<script>
// 网络请求
import axios from '../utils/request'
// 用来显示朋友圈时间的转换
import {weChatTimeFormat} from '@/utils/time.js'
// 显示加载框等
import {Toast} from 'vant';
// 预览图片组件，vantui的
import {ImagePreview} from 'vant';
import Vue from 'vue';
import { Lazyload } from 'vant';

Vue.use(Lazyload);
export default {
  data() {
    return {
      images:[],
      showReplys: false,
      actions: [
        {id: 1, name: '回复'},
        {id: 2, name: '删除', color: '#ee0a24'}
      ],
      list: [],//要显示的圈子数据
      page: 1,
      refreshing: false,
      total: 1,//表示总页码数
      showComment: false,
      showReplyComment: false,//控制显示回复的输入框
      circleId: 0,//用来存储当前操作的圈子ID
      comment: '',//评论的内容
      index: 0,//用来存储当前操作的圈子数组下标
      circleItem: {},//用来存储当前操作的圈子实体
      commentItem: {},//用来存储当前操作的评论实体
      userInfo: {}
    };
  },
  mounted() {//生命周期函数，刷新页面会调用
    this.getList()
    //取接口的数据
    axios.get("/getUser").then(response => {
      this.userInfo = response.data.data
    })
    //取接口的数据
    axios.get("/getBanner").then(response => {
      this.images = []
      for (const responseElement of response.data.data) {
        this.images.push(responseElement.url)
      }
      // this.images = response.data.data
    })
  },
  methods: {
    onSelect(item) {
      if (item.id == 1) {//回复
        this.showReplyComment = true//显示回复输入框
        this.showReplys = false //隐藏回复弹出框
      } else {//删除
        //调用后台删除评论接口
        // /circle/delComment
        let data = {
          id: this.commentItem.id
        };
        axios
            .post("/circle/delComment", data)
            .then((response) => {
              Toast.success(response.data.msg);
              //获取评论接口
              axios.get("/circle/getCommentList?id=" + this.list[this.index].id).then(response => {
                this.list[this.index].comments = response.data.data // 获取最新的评论列表
              })

            })

      }
    },
    //点击评论弹出框
    showReply(item, index) {
      if (item.user_id == this.userInfo.id) {//自己发的可以删除
        this.actions = [
          {id: 1, name: '回复'},
          {id: 2, name: '删除', color: '#ee0a24'}
        ]
      } else {
        this.actions = [
          {id: 1, name: '回复'}
        ]
      }
      this.showReplys = true;//显示对话框
      this.commentItem = item //把当前操作的评论实体存到commentItem
      this.index = index //保存当前操作的圈子在数组中的下标
      this.circleId = this.list[index].id
    },
    //评论 或者回复评论
    Comment() {
      let data = {
        circleId: this.circleId,
        content: this.comment,
        replyId: this.commentItem.id ? this.commentItem.id : 0  //评论的时候给0  回复评论的时候给回复的评论ID
      };
      axios
          .post("/circle/comment", data)
          .then((response) => {
              this.comment = ""
              this.showComment = false;//隐藏弹出框
              this.showReplyComment = false//隐藏弹出框
              this.commentItem = {} //重置
              Toast.success(response.data.msg);

              axios.get("/circle/getCommentList?id=" + this.circleId).then(response => {

                  this.list[this.index].comments = response.data.data // 获取最新的评论列表

              })
          });
    },
    //显示评论对话框
    showComments(item, index) {
      this.showComment = true;//显示对话框
      item.showPopover = false//隐藏
      this.circleId = item.id
      this.index = index
    },

    //点赞
    like(item, index) {
      //提交参数
      let data = {
        circleId: item.id,//点赞的圈子ID
        status: item.status == 1 ? 0 : 1//状态1 表示是点赞
      }
      axios.post("/circle/like", data).then(response => {
          axios.get("/circle/getLikeUsers?id=" + item.id).then(response => {
              item.likeUsers = response.data.data // 获取最新的点赞用户列表
          })
          item.showPopover = false // 隐藏点赞弹出框
          item.status = item.status == 1 ? 0 : 1//修改状态，让点赞图标变颜色
          // Vue.set(this.list, index, item);
          // Toast.success(response.data.msg);
      })
    },
    //格式化时间，显示朋友圈风格的时间
    parse(time) {
      return weChatTimeFormat(time)
    },
    //预览图片 list是要显示的图片列表 index是位置，表示进去后显示的是第几张
    ImagePreview(list, index) {
      ImagePreview({
        images: list,
        startPosition: index,
      });
    },
    //前往发布页面
    goPublic() {
      this.$router.push('/public')
    },
    //下拉刷新触发
    onRefresh() {
      this.page = 1//充值页码
      this.list = []//重置列表数组
      this.getList();
    },
    //滑动到底部触发
    onLoad() {
      if (this.page == this.total) {
        return
      }
      this.page++ //请求下一页的数据
      this.getList();
    },
    //请求后台获取数据列表
    getList() {
      axios.get("/circle/list?page=" + this.page).then(response => {
        this.refreshing = false

          for (const item of response.data.data.list) {//处理图片数据，因为存入数据库的数据是字符串
            item.showPopover = false
            if (!item.comments) {
              item.comments = []
            }
            if (!item.images) {//如果数据库中存的的图片是null或者空字符串
              item.images = []//赋值空数组
              continue//处理下一条数据
            }
            // item.status = 0//设置点赞状态为0，默认为没有点赞
            item.images = JSON.parse(item.images)//字符串转对象
          }
          this.list = [...this.list, ...response.data.data.list]//获取列表 合并两个数组
          this.total = response.data.data.total

      })
    }

  }
}
</script>

<style>
.flex {
  flex: 1
}

.common {
  padding: 12px 24px;
  align-items: center;
  font-size: 14px;
}

.username {
  color: #194e83;
  font-weight: 550;
  font-size: 17px;
}

.content-text {
  color: #000000;
  font-size: 15px;
  margin-top: 5px;
  font-family: '微软雅黑', '宋体';
}

.timestamp {
  color: #999999;
  font-size: 11px;

}

.y {
  display: flex;
  flex-direction: column;
}

.x {
  display: flex;
  flex-direction: row;
}

.likeUsers {
  padding: 8px 12px;
  background: #eee;
  font-size: 14px;
  color: #0c3a96;
  margin-top: 6px;
  border-radius: 4px;
}

.common-root {
  background: #eee;
  border-radius: 2px;
  padding: 6px 10px;
  display: flex;
  flex-direction: column;
  border-top: 1px solid #ddd;
}

.common-friends {
  display: flex;
  margin-top: 4px;
  flex-direction: row;
  align-items: start;
}

.common-friends :hover {
  background: #ccc;
}

.common-content {
  color: #333333;
  font-size: 14px;
  word-break: break-all
}

.common-nickname {
  margin-right: 5px;
  color: #284bad;
  font-size: 14px;
  font-weight: 700;
  font-family: "微软雅黑", "宋体";
}
</style>